package study.alex.resumedb.gae;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.oauth2.Oauth2;
import com.google.api.services.oauth2.model.Userinfo;
import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.data.Property;
import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.View;
import com.vaadin.server.*;
import com.vaadin.ui.*;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import study.alex.resumedb.gae.backend.Broadcaster;
import study.alex.resumedb.gae.feeds.VacancyFeed;
import study.alex.resumedb.gae.feeds.VacancyFeedFactory;

import java.io.*;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

@Theme("mytheme")
@SuppressWarnings("serial")
public class ResumeDBMaintUI extends UI implements Serializable, Broadcaster.BroadcastListener
{
    private static final Logger log = Logger.getLogger(ResumeDBMaintUI.class.getName());
    private static final String ROOT_URL = "https://sanguine-healer-433.appspot.com/";

    private static final String VERSION = "1.0";
    private static final String APP_NAME = "ResumeDB v" + VERSION;

    private Navigator navigator;

    private transient ResourceBundle resourceBundle;
    private Locale userLocale;
    private View mainView;

    private void readObject(java.io.ObjectInputStream stream)
            throws java.io.IOException, ClassNotFoundException
    {
        stream.defaultReadObject();

        // assign reference manually.

        log.fine("Current Locale: " + getUserLocale().getDisplayCountry());
        try {
            resourceBundle = ResourceBundle.getBundle("study.alex.resumedb.gae.resumedb", getUserLocale());
            log.fine("Using resource bundle with locale: " + resourceBundle.getLocale().getDisplayCountry());
        } catch (MissingResourceException e) {
            userLocale = new Locale("en", "EN");
            resourceBundle = ResourceBundle.getBundle("study.alex.resumedb.gae.resumedb", userLocale);
            setLocale(userLocale);
            log.fine("Resource bundle missing.  Using Locale: " + userLocale.getDisplayCountry());
            log.fine("Using resource bundle with locale: " + resourceBundle.getLocale().getDisplayCountry());
        }
    }

    public ResourceBundle getBundle() {
        if (resourceBundle != null) return resourceBundle;
        else return ResourceBundle.getBundle("study.alex.resumedb.gae.resumedb", new Locale("en", "EN"));
    }

    public Locale getUserLocale() {
        if (userLocale != null) return userLocale;
        else return new Locale("en", "EN");
    }

    @Override
    public void receiveBroadcast(String message) {
        if (mainView != null) ((MainViewPanel)mainView).receiveBroadcast(message);
    }

    @Override
    protected void init(VaadinRequest request) {

        userLocale = request.getLocale();
        log.info("Current Locale: " + userLocale.getDisplayCountry());
        try {
            resourceBundle = ResourceBundle.getBundle("study.alex.resumedb.gae.resumedb", userLocale);
            log.info("Using resource bundle with locale: " + resourceBundle.getLocale().getDisplayCountry());
        } catch (MissingResourceException e) {
            userLocale = new Locale("en", "EN");
            resourceBundle = ResourceBundle.getBundle("study.alex.resumedb.gae.resumedb", userLocale);
            setLocale(userLocale);
            log.info("Resource bundle missing.  Using Locale: " + userLocale.getDisplayCountry());
            log.info("Using resource bundle with locale: " + resourceBundle.getLocale().getDisplayCountry());
        }

        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user == null) {

            Notification.show(((ResumeDBMaintUI) UI.getCurrent()).getBundle().getString("firstly.you.need.to.login.via.google"), "", Notification.Type.HUMANIZED_MESSAGE);

            //User didn't login
            getUI().getPage().setLocation(ROOT_URL);
            // Close the VaadinSession
            getSession().close();
            log.info("User didn't log in");
            return;
        }

        GoogleServices services = new GoogleServices(user.getUserId());
        Credential diskCredential = services.getCredential();

        if (diskCredential == null)
            Notification.show(((ResumeDBMaintUI) UI.getCurrent()).getBundle().getString("google.disk.access.is.not.granted"), ((ResumeDBMaintUI) UI.getCurrent()).getBundle().getString("store.resume.file.and.preview.option.isn.t.allowed"), Notification.Type.WARNING_MESSAGE);

        log.fine("Current namespace is " + NamespaceManager.get());
        log.fine("DiskCredential is " + diskCredential);

        getPage().setTitle(APP_NAME);

//        VaadinSession.getCurrent().setConverterFactory(new AppConverterFactory());

        navigator = new Navigator(this, this);

        mainView = new MainViewPanel(this, user.getUserId(), ROOT_URL, services);
        navigator.addView("", mainView);

        Broadcaster.register(this);
    }

    @Override
    public void detach() {
        Broadcaster.unregister(this);
        super.detach();
    }
}

